package com.example.medicalapp.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.medicalapp.R;
import com.example.medicalapp.adapter.AppointmentAdapter;
import com.example.medicalapp.helper.DatabaseHelper;
import com.example.medicalapp.model.Appointment;
import com.example.medicalapp.util.PreferencesUtil;
import java.util.List;

public class PatientAppointmentActivity extends AppCompatActivity {
    private static final String TAG = "PatientAppointmentActivity";

    private RecyclerView rvAppointments;
    private AppointmentAdapter adapter;
    private TextView tvEmpty;
    private DatabaseHelper dbHelper;
    private PreferencesUtil preferencesUtil;
    private int patientId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_patient_appointment);
            Log.d(TAG, "onCreate called");

            // 初始化视图
            initViews();

            // 初始化工具类
            initHelpers();

            // 加载挂号记录
            loadAppointments();
        } catch (Exception e) {
            Log.e(TAG, "Error in onCreate: " + e.getMessage(), e);
            Toast.makeText(this, "加载失败，请重试", Toast.LENGTH_SHORT).show();
            finish(); // 出现严重错误时关闭当前页面
        }
    }

    private void initViews() {
        try {
            tvEmpty = findViewById(R.id.tv_empty);
            rvAppointments = findViewById(R.id.rv_appointments);
            rvAppointments.setLayoutManager(new LinearLayoutManager(this));
            // 设置空视图提示文字
            tvEmpty.setText("您暂无挂号记录");
        } catch (Exception e) {
            Log.e(TAG, "Error initializing views: " + e.getMessage(), e);
            throw e; // 传递异常以便上层处理
        }
    }

    private void initHelpers() {
        try {
            dbHelper = new DatabaseHelper(this);
            preferencesUtil = new PreferencesUtil(this);

            // 安全获取用户ID
            patientId = preferencesUtil.getUserId();
            if (patientId <= 0) {
                Log.e(TAG, "Invalid patient ID: " + patientId);
                Toast.makeText(this, "用户信息获取失败", Toast.LENGTH_SHORT).show();
                finish(); // 用户ID无效时关闭页面
            }
        } catch (Exception e) {
            Log.e(TAG, "Error initializing helpers: " + e.getMessage(), e);
            throw e;
        }
    }

    private void loadAppointments() {
        try {
            // 检查数据库连接
            if (dbHelper == null) {
                Log.e(TAG, "Database helper is null");
                showEmptyState();
                return;
            }

            // 从数据库获取挂号记录
            List<Appointment> appointments = dbHelper.getAppointmentsByPatient(patientId);
            Log.d(TAG, "Loaded " + appointments.size() + " appointments for patient: " + patientId);

            // 处理空记录情况
            if (appointments == null || appointments.isEmpty()) {
                showEmptyState();
                return;
            }

            // 显示记录列表
            showAppointmentsList(appointments);
        } catch (Exception e) {
            Log.e(TAG, "Error loading appointments: " + e.getMessage(), e);
            Toast.makeText(this, "获取挂号记录失败", Toast.LENGTH_SHORT).show();
            showEmptyState();
        }
    }

    private void showAppointmentsList(List<Appointment> appointments) {
        tvEmpty.setVisibility(View.GONE);
        rvAppointments.setVisibility(View.VISIBLE);

        adapter = new AppointmentAdapter(appointments, dbHelper, this::onAppointmentClick);
        rvAppointments.setAdapter(adapter);
    }

    private void showEmptyState() {
        tvEmpty.setVisibility(View.VISIBLE);
        rvAppointments.setVisibility(View.GONE);
    }

    private void onAppointmentClick(Appointment appointment) {
        try {
            Log.d(TAG, "Appointment clicked: " + appointment.getId());
            // 可以添加查看详情的逻辑
        } catch (Exception e) {
            Log.e(TAG, "Error handling appointment click: " + e.getMessage(), e);
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保数据库连接关闭
        if (dbHelper != null) {
            try {
                dbHelper.close();
            } catch (Exception e) {
                Log.e(TAG, "Error closing database: " + e.getMessage(), e);
            }
        }
        Log.d(TAG, "onDestroy called");
    }
}
